package com.yidu.web.dao;

import com.yidu.web.model.User;
import com.yidu.web.model.WsJoke;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 信息dao
 */
public class WsJokeDao {

    /**
     * 增加
     * @param joke
     * @return
     */
    public int insert(WsJoke joke) {
        Connection con = null;
        PreparedStatement statement = null;

        try {
            con = JDBCTools.getCon();
            String sql = "insert into ws_joke(joke_id,title,content,url,flag) values (null, ?, ?, ?, ?)";
            System.out.println("正在执行sql:"+sql);
            statement = con.prepareStatement(sql);
            statement.setString(1, joke.getTitle());
            statement.setString(2, joke.getContent());
            statement.setString(3, joke.getUrl());
            statement.setString(4,joke.getFlag()); //默认离线
            return statement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.close(con, statement);
        }
        return 0;
    }

    /**
     * 找到所有的标识
     * @return
     */
    public Map<String,WsJoke> findFlag(){
        Map<String,WsJoke> map = new HashMap<>();
        Connection con = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            con = JDBCTools.getCon();
            String sql = "select * from ws_joke ";
            statement = con.prepareStatement(sql);

            rs = statement.executeQuery();
            while (rs.next()) {
                WsJoke wsJoke = new WsJoke();
                String key = rs.getString("flag");
                Integer jokeId = rs.getInt("joke_id");
                String title = rs.getString("title");
                String content = rs.getString("content");

                wsJoke.setFlag(key);
                wsJoke.setJokeId(jokeId);
                wsJoke.setTitle(title);
                wsJoke.setContent(content);

                map.put(key,wsJoke);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.close(con, statement, rs);
        }
        return map ;
    }
}
